package com.blb.zycommunity.entity;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 向前端返回统一实体对象
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ResponseResult<T> {
    private Long code;
    private String message;
    private T data;

    /**
     * 返回正常的数据
     * @param <T>
     * @return
     */
    public static <T> ResponseResult ok(T data){
        return new ResponseResult(200l,"",data);
    }


    /**
     * 返回错误信息
     * @param code
     * @param message
     * @param <T>
     * @return
     */
    public static <T> ResponseResult error(Long code,String message){
        return new ResponseResult(code,message,null);
    }

    /**
     * 将JSON数据发送给前端
     * @param <T>
     */
    public static <T> void write(ResponseResult result, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        //将对象转化为json字符串
        String json = new ObjectMapper().writeValueAsString(result);
        //将json通过输出流发送给前端
        response.getWriter().write(json);
        //关闭流
        response.getWriter().close();
    }

}
